# coding=utf-8
import json

from aliyunsdkasapi.ASClient import ASClient
from aliyunsdkasapi.AsapiRequest import AsapiRequest

from model.c_cloud import find_cloud_by_id


def request_asapi(cloud_id, product, version, action_name, params=None, ak=None, sk=None):
    """
    直接获取asapi接口返回，解析为python对象后返回
    :param cloud_id:
    :param product:
    :param version:
    :param action_name:
    :param params:
    :return: 返回一个python对象，使用json解析asapi原生接口的内容
    """
    # 先去数据库里查询这个云的信息
    cloud = find_cloud_by_id(cloud_id)
    region = cloud['region_id']
    endpoint = cloud['asapi_endpoint']
    if not (ak and sk):
        # 对于cms，需要传入一级部门的ak sk
        ak = cloud['root_access_key_id']
        sk = cloud['root_access_key_secret']

    # 创建ASClient连接,timeout设置请求超时时间，cert_file设置证书文件，verify是否验证证书
    client = ASClient(ak, sk, region, timeout=100000, cert_file=None, verify=False)
    # 设置身份标识,标识调用来源,无实际作用,可随意设置,必填项
    client.setSdkSource("asapi-4548@asapi-inc.com")
    # ASAPI的Endpoint地址

    # 创建Request
    request = AsapiRequest(product, version, action_name, endpoint)
    # 设置请求方式
    request.set_method("POST")
    # 授权相关参数

    # 接口业务参数设置

    if params:
        for k, v in params.items():
            request.add_body_params(k, v)

    # 设置Headers
    # 部分接口需要在页面headers列表中填写x-acs-organizationId、x-acs-resourceGroupId等组织，资源组信息

    # 对ASAPI发起请求，并获取返回
    response = client.do_request(request)
    # try:
    #     response = client.do_action_with_exception(request)
    # except ServerException as e:
    #     # 这里可以添加您自己的错误处理逻辑
    #     # 例如，打印具体的错误信息
    #     print(e.get_http_status())
    #     print e.get_error_code()
    #     print e.get_error_msg()

    res = str(response, encoding='utf-8')
    data = {}
    try:
        data = json.loads(res)
        print("ASAPI -> {} {} {} <- Success: {}".format(product, action_name, params, data['asapiSuccess']))
    except Exception as e:
        print("ASAPI 原始返回：", res)
        print("ASAPI json解析错误：", e)
    return data
